package cn.cool.webserver;

import cn.cool.entity.Message;
import cn.cool.utils.RedisUtil;
import com.alibaba.fastjson.JSON;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.swagger.annotations.Api;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.Date;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author LiuH
 * @create 2021-01-29 下午 3:24
 */

@ServerEndpoint("/chat/websocket/{userId}") //连接地址
@Api(tags = "websocket接口")
@Component
public class WebSocketServer {

    @Autowired
    private RedisUtil redisUtil;

    //存放每个客户端对应的WebSocketServer对象 注:Session是websocket包下的
    //当前连接上的用户
    private static ConcurrentHashMap<Integer, Session> sessionPool = new ConcurrentHashMap<>();


    //连接成功建立时调用
    @OnOpen
    public void onOpen(Session session, @PathParam("userId") Integer userId) {

        sessionPool.put(userId, session);//将连接上的用户存入sessionPool

        System.out.println(userId + "--连上了websocket");

    }

    //关闭连接时调用
    @OnClose
    public void Onclose(@PathParam("userId") Integer userId) {

        sessionPool.remove(userId);//根据用户id 移除session

        System.out.println(userId + "--与websocket断开连接");

    }

    //收到客户端信息后  发送给接收方
    @OnMessage
    public void onMessage(String message) {

        Message msg = JSON.parseObject(message, Message.class);
        msg.setDate(new Date());//发送日期
        //判断接收方是否在线
        Session toUser = sessionPool.get(msg.to);

        if (toUser == null) {
            //存入离线消息表
        } else {
            //发送信息
            sendInfo(msg.getTo(), JSON.toJSONString(msg, true));
        }

    }

    //错误时调用
    @OnError
    public void onError(Session session, Throwable throwable) {
        System.out.println("发生错误");
    }

    //给指定用户uid发送信息
    public void sendInfo(Integer uid, String message) {
        Session session = sessionPool.get(uid);
        try {
            session.getBasicRemote().sendText(message);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}
